﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SIGBugs.Server.DataAccess;
using SIGBugs.Shared.ViewModels;

namespace SIGBugs.Server.Controllers
{
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class TasksController : Controller
    {
        private readonly BugsContext _context;

        public TasksController(BugsContext context)
        {
            _context = context;
        }

        // GET: api/Tasks
        [HttpGet("[action]/{projectId}")]
        [Authorize]
        public async Task<PageTaskVM> GetTasks(int projectId)
        {
            PageTaskVM vm = new PageTaskVM
            {
                Project = await _context.Projects.Where(d => d.Id == projectId).Select(d => new ProjectVM
                {
                    Id = d.Id,
                    Name = d.Name,
                    Description = d.Description,
                    CreatedBy = d.CreatedBy,
                    CreatedDate = d.CreatedDate
                }).FirstOrDefaultAsync(),

                Tasks = await _context.Tasks.AsNoTracking()
                .Where(d => d.ProjectId == projectId)
                .Select(d => new TaskVM
                {
                    Id = d.Id,
                    Title = d.Title,
                    Status = d.Status,
                    TaskType = d.TaskType,
                    StatusText = d.StatusText,
                    TypeText = d.TypeText,
                    CreatedBy = d.CreatedBy,
                    CreatedDate = d.CreatedDate
                }).ToListAsync()
            };

            return vm;
        }

        // GET: api/Tasks/5
        [HttpGet("{id}")]
        public async Task<IActionResult> GetTask([FromRoute] int id)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var task = await _context.Tasks.FindAsync(id);

            if (task == null)
            {
                return NotFound();
            }

            return Ok(task);
        }

        // PUT: api/Tasks/5
        [HttpPut("{id}")]
        public async Task<IActionResult> PutTask([FromRoute] int id, [FromBody] Shared.Models.Task task)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != task.Id)
            {
                return BadRequest();
            }

            _context.Entry(task).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TaskExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/Tasks
        [HttpPost]
        public async Task<IActionResult> PostTask([FromBody] Shared.Models.Task task)
        {
           

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            _context.Tasks.Add(task);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetTask", new { id = task.Id }, task);
        }

        // DELETE: api/Tasks/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteTask([FromRoute] int id)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var task = await _context.Tasks.FindAsync(id);
            if (task == null)
            {
                return NotFound();
            }

            _context.Tasks.Remove(task);
            await _context.SaveChangesAsync();

            return Ok(task);
        }

        private bool TaskExists(int id)
        {
            return _context.Tasks.Any(e => e.Id == id);
        }
    }
}